package org.example.web.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.model.entity.*;
import org.example.model.enums.ItemType;
import org.example.web.admin.mapper.*;
import org.example.web.admin.service.*;
import org.example.web.admin.vo.apartment.ApartmentDetailVo;
import org.example.web.admin.vo.apartment.ApartmentItemVo;
import org.example.web.admin.vo.apartment.ApartmentQueryVo;
import org.example.web.admin.vo.apartment.ApartmentSubmitVo;
import org.example.web.admin.vo.fee.FeeValueVo;
import org.example.web.admin.vo.graph.GraphVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {
    //apartment_info：公寓基本信息表
    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;
    //apartment_facility: 公寓配套信息数据
    @Autowired
    private ApartmentFacilityService apartmentFacilityService;
    //apartment_label：公寓标签数据
    @Autowired
    private ApartmentLabelService apartmentLabelService;
    //apartment_fee_value：公寓杂费数据
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;
    //graph_info：图片表graph_info
    @Autowired
    private GraphInfoService graphInfoService;
    //room_info：房间信息表
    @Autowired
    private RoomInfoService roomInfoService;

    @Autowired
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired
    private LabelInfoMapper labelInfoMapper;
    @Autowired
    private FeeValueMapper feeValueMapper;
    @Autowired
    private GraphInfoMapper graphInfoMapper;

    @Override
    public void saveOrUpdateApartment(ApartmentSubmitVo apartmentSubmitVo) {
        //根据主键判断是否为更新
        boolean updateFlag = StrUtil.isEmptyIfStr(apartmentSubmitVo.getId());
        //无论是插入还是更新操作,都应该先对主表进行操作
        saveOrUpdate(apartmentSubmitVo);
        //更新的情况下需要对子表进行删除处理后再进行添加
        if (updateFlag) {
            //从语义上来说,LambdaUpdateWrapper更适合于UPDATE操作

            //删除公寓配套信息数据
            LambdaUpdateWrapper<ApartmentFacility> filterWrapper = new LambdaUpdateWrapper<>();
            filterWrapper.eq(ApartmentFacility::getApartmentId, apartmentSubmitVo.getId());
            apartmentFacilityService.remove(filterWrapper);

            //删除公寓标签数据
            LambdaUpdateWrapper<ApartmentLabel> lambdaWrapper = new LambdaUpdateWrapper<>();
            lambdaWrapper.eq(ApartmentLabel::getApartmentId, apartmentSubmitVo.getId());
            apartmentLabelService.remove(lambdaWrapper);

            //删除公寓杂费数据
            LambdaUpdateWrapper<ApartmentFeeValue> feeWrapper = new LambdaUpdateWrapper<>();
            feeWrapper.eq(ApartmentFeeValue::getApartmentId, apartmentSubmitVo.getId());
            apartmentFeeValueService.remove(feeWrapper);

            //删除公寓图片数据
            LambdaUpdateWrapper<GraphInfo> graphWrapper = new LambdaUpdateWrapper<>();
            graphWrapper.eq(GraphInfo::getItemId, apartmentSubmitVo.getId());
            //只需要删除枚举类型为公寓的图片数据
            graphWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
            graphInfoService.remove(graphWrapper);
        }

        //公寓配套数据ids集合
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        if (!CollectionUtils.isEmpty(facilityInfoIds)) {
            List<ApartmentFacility> apartmentFacilities = new ArrayList<>();
            facilityInfoIds.forEach(facilityInfoId -> {
                ApartmentFacility apartmentFacility = ApartmentFacility.builder()
                        .apartmentId(apartmentSubmitVo.getId())
                        .facilityId(facilityInfoId)
                        .build();
                apartmentFacilities.add(apartmentFacility);
            });
            apartmentFacilityService.saveBatch(apartmentFacilities);
        }

        //公寓标签数据ids集合
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        if (!CollectionUtils.isEmpty(labelIds)) {
            List<ApartmentLabel> apartmentLabels = new ArrayList<>();
            labelIds.forEach(labelId -> {
                ApartmentLabel apartmentLabel = ApartmentLabel.builder()
                        .apartmentId(apartmentSubmitVo.getId())
                        .labelId(labelId)
                        .build();
                apartmentLabels.add(apartmentLabel);
            });
            apartmentLabelService.saveBatch(apartmentLabels);
        }

        //公寓杂费数据ids集合
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        if (!CollectionUtils.isEmpty(feeValueIds)) {
            List<ApartmentFeeValue> apartmentFeeValues = new ArrayList<>();
            feeValueIds.forEach(feeValueId -> {
                ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder()
                        .apartmentId(apartmentSubmitVo.getId())
                        .feeValueId(feeValueId)
                        .build();
                apartmentFeeValues.add(apartmentFeeValue);
            });
            apartmentFeeValueService.saveBatch(apartmentFeeValues);
        }

        //公寓图片数据ids集合
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        if (!CollectionUtils.isEmpty(graphVoList)) {
            List<GraphInfo> graphInfos = new ArrayList<>();
            graphVoList.forEach(graphVo -> {
                GraphInfo graphInfo = GraphInfo.builder()
                        .itemId(apartmentSubmitVo.getId())
                        .itemType(ItemType.APARTMENT)
                        .name(graphVo.getName())
                        .url(graphVo.getUrl())
                        .build();
                graphInfos.add(graphInfo);
            });
        }
    }

    @Override
    public ApartmentDetailVo getDetailById(Long id) {
        ApartmentInfo apartmentInfo = getById(id);
        if (apartmentInfo == null) {
            return null;
        }

        //配套
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.findFacilityListByApartmentId(id);
        //标签
        List<LabelInfo> labelInfoList = labelInfoMapper.findLabelListByApartmentId(id);
        //杂费
        List<FeeValueVo> feeValueVoList = feeValueMapper.findFeeValueListByApartmentId(id);
        //图片
        List<GraphVo> graphVoList = graphInfoMapper.findGraphListByItemIdAndItemType(id, ItemType.APARTMENT);

        ApartmentDetailVo vo = new ApartmentDetailVo();
        BeanUtils.copyProperties(apartmentInfo,vo);
        vo.setFacilityInfoList(facilityInfoList);
        vo.setLabelInfoList(labelInfoList);
        vo.setFeeValueVoList(feeValueVoList);
        vo.setGraphVoList(graphVoList);

        return vo;
    }

    @Override
    public IPage<ApartmentItemVo> selectApartmentInfoPage(Page<ApartmentItemVo> page,
                                                          ApartmentQueryVo queryVo) {
        IPage<ApartmentItemVo> pageModel = apartmentInfoMapper.selectApartmentInfoPage(page,queryVo);
        return pageModel;
    }

    @Override
    public void removeApartmentInfo(Long id) {
        //子表有数据的情况下不能删除主表数据
        LambdaQueryWrapper<RoomInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoomInfo::getApartmentId,id);
        long count = roomInfoService.count(wrapper);
        if(count > 0) { //存在房间信息
            throw new RuntimeException("存在房间信息，不能删除");
        }
        //删除公寓基本信息
        this.removeById(id);
        //删除配套
        LambdaQueryWrapper<ApartmentFacility> facilityQueryWrapper =  new LambdaQueryWrapper<>();
        facilityQueryWrapper.eq(ApartmentFacility::getApartmentId,id);
        apartmentFacilityService.remove(facilityQueryWrapper);
        //删除标签
        LambdaQueryWrapper<ApartmentLabel> labelQueryWrapper = new LambdaQueryWrapper<>();
        labelQueryWrapper.eq(ApartmentLabel::getApartmentId, id);
        apartmentLabelService.remove(labelQueryWrapper);
        //删除杂费
        LambdaQueryWrapper<ApartmentFeeValue> feeQueryWrapper = new LambdaQueryWrapper<>();
        feeQueryWrapper.eq(ApartmentFeeValue::getApartmentId, id);
        apartmentFeeValueService.remove(feeQueryWrapper);
        //删除图片
        LambdaQueryWrapper<GraphInfo> graphQueryWrapper = new LambdaQueryWrapper<>();
        graphQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
        graphQueryWrapper.eq(GraphInfo::getItemId, id);
        graphInfoService.remove(graphQueryWrapper);
    }

    @Override
    public List<ApartmentInfo> listInfoByDistrictId(Long id) {
        List<ApartmentInfo> list = apartmentInfoMapper.listInfoByDistrictId(id);
        return list;
    }
}




